<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !repairDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-notRepairTransferToThirdValue>
            <SelectModel
              v-model="filterInfo.query.queryParams.notRepairTransferToThird"
              :checkDefault="false"
              placeholder="请选择是否院外"
              typeCode="yes_or_no"
              :clearable="true"
              @change="search"
            />
          </template>
        </NewPageFilter>
      </div>

      <div class="filter-wrapper" style="padding-bottom: 10px">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <p class="slip-edit" @click="showProductDetail(scope.row)">
            {{ scope.row.orderNo || '-' }}
          </p>
        </template>
        <template v-slot:col-repairNo="scope">
          <p class="slip-edit" @click="showRepairDetail(scope.row)">
            {{ scope.row.repairNo || '-' }}
          </p>
        </template>
      </table-container>
    </div>
    <!-- 新增或修改 -->
    <MaintenanceOrderModify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 详情页 -->
    <maintenanceOrder-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />
    <repairOrder-detail
      v-if="repairDetailInfo.visible"
      :id="repairDetailInfo.id"
      v-model:visible="repairDetailInfo.visible"
      :title="repairDetailInfo.title"
      :noOrderType="true"
      @returnBack="getList"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />

    <!-- 转交 -->
    <page-dialog
      v-show="turnOverInfo.visible"
      :title="turnOverInfo.title"
      v-model:visible="turnOverInfo.visible"
      :width="turnOverInfo.width"
      :bt-loading="turnOverInfo.btLoading"
      :bt-list="turnOverInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="turnOverInfo.formInfo.ref"
        :data="turnOverInfo.formInfo.data"
        :field-list="turnOverInfo.formInfo.fieldList"
        :rules="turnOverInfo.formInfo.rules"
        :label-width="turnOverInfo.formInfo.labelWidth"
      >
        <template v-slot:form-acceptUserName>
          <el-input
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维修人员"
            v-model="turnOverInfo.formInfo.data.acceptUserName"
          >
            <template #append>
              <el-icon @click="openRepairUserWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!-- 维修人员 -->
    <SelectRepairUser
      v-if="selectRepairUserInfo.visible"
      v-model:showDialog="selectRepairUserInfo.visible"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectRepairUserInfo.api"
      :query="selectRepairUserInfo.query"
      @callback="selectRepairUserCallBack"
    />
    <!-- 处理登记 -->
    <page-dialog
      v-show="registerInfo.visible"
      :title="registerInfo.title"
      v-model:visible="registerInfo.visible"
      :width="registerInfo.width"
      :bt-loading="registerInfo.btLoading"
      :bt-list="registerInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="registerInfo.formInfo.ref"
        :data="registerInfo.formInfo.data"
        :field-list="registerInfo.formInfo.fieldList"
        :rules="registerInfo.formInfo.rules"
        :label-width="registerInfo.formInfo.labelWidth"
      >
        <template v-slot:form-startTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-endTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-filePathList>
          <el-upload
            :headers="registerInfo.uploadInfo.headers"
            :on-error="uploadError"
            :on-success="uploadAttachment"
            :on-remove="uploadRemove"
            :before-upload="beforeProductUpload"
            :on-exceed="handleExceed"
            :action="registerInfo.uploadInfo.action"
            :limit="registerInfo.uploadInfo.limit"
            :file-list="registerInfo.uploadInfo.fileList"
          >
            <el-button>点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              文件大小不超过{{
                $store.state.permission.systemConfig.max_file_size
              }}M
            </div>
          </el-upload>
        </template>
      </page-form>
    </page-dialog>
    <!-- 完工 -->
    <page-dialog
      v-show="finishInfo.visible"
      :title="finishInfo.title"
      v-model:visible="finishInfo.visible"
      :width="finishInfo.width"
      :bt-loading="finishInfo.btLoading"
      :bt-list="finishInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="finishInfo.formInfo.ref"
        :data="finishInfo.formInfo.data"
        :field-list="finishInfo.formInfo.fieldList"
        :rules="finishInfo.formInfo.rules"
        :label-width="finishInfo.formInfo.labelWidth"
      >
        <template v-slot:form-completeTime>
          <el-date-picker
            v-model="finishInfo.formInfo.data.completeTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
      </page-form>
    </page-dialog>
    <!-- 故障确认 -->
    <page-dialog
      v-show="faultVerifyInfo.visible"
      :title="faultVerifyInfo.title"
      v-model:visible="faultVerifyInfo.visible"
      :width="faultVerifyInfo.width"
      :bt-loading="faultVerifyInfo.btLoading"
      :bt-list="faultVerifyInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="faultVerifyInfo.formInfo.ref"
        :data="faultVerifyInfo.formInfo.data"
        :field-list="faultVerifyInfo.formInfo.fieldList"
        :rules="faultVerifyInfo.formInfo.rules"
        :label-width="faultVerifyInfo.formInfo.labelWidth"
      >
        <template v-slot:form-faultTime>
          <el-date-picker
            v-model="faultVerifyInfo.formInfo.data.faultTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-faultPart>
          <el-input
            v-model="faultVerifyInfo.formInfo.data.faultPart"
            type="input"
            class="not-mongolia"
            placeholder="请输入/选择故障部位"
          >
            <template #append>
              <el-icon @click="openAssetResource"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-faultDescribe>
          <el-input
            :style="{
              width: $permission('repairOrder:selectFaultLib') ? '86%' : '100%',
            }"
            v-model="faultVerifyInfo.formInfo.data.faultDescribe"
            type="textarea"
            :rows="1"
            class="not-mongolia"
            placeholder="请输入故障描述"
          >
          </el-input>
          <el-tooltip
            v-if="$permission('repairOrder:selectFaultLib')"
            effect="dark"
            content="从故障库选择"
            placement="top-start"
          >
            <el-icon style="font-size: 20px; cursor: pointer" @click="openFault"
              ><CirclePlus
            /></el-icon>
          </el-tooltip>
        </template>
        <template v-slot:form-maintenanceScheme>
          <el-input
            :style="{
              width: $permission('maintenanceOrder:addFaultLib')
                ? '86%'
                : '100%',
            }"
            v-model="faultVerifyInfo.formInfo.data.maintenanceScheme"
            type="textarea"
            :rows="1"
            class="not-mongolia"
            placeholder="请输入维修方案"
          >
          </el-input>
          <el-tooltip
            v-if="$permission('maintenanceOrder:addFaultLib')"
            effect="dark"
            content="加入故障库"
            placement="top-start"
          >
            <el-icon style="font-size: 20px; cursor: pointer" @click="_addFault"
              ><CirclePlus
            /></el-icon>
          </el-tooltip>
        </template>
      </page-form>
    </page-dialog>
    <!-- 配件使用 -->
    <page-dialog
      v-show="mountingsUseInfo.visible"
      :title="mountingsUseInfo.title"
      v-model:visible="mountingsUseInfo.visible"
      :width="mountingsUseInfo.width"
      :bt-loading="mountingsUseInfo.btLoading"
      :bt-list="mountingsUseInfo.btList"
    >
      <NewPageFilter
        v-model:query="mountingsUseInfo.filterInfo.query"
        :filter-btn="mountingsUseInfo.filterInfo.list"
      >
        <template v-slot:filter-removeMountings>
          <el-button
            :disabled="!mountingsUseInfo.tableInfo.selections.length"
            @click="removeMountings(undefined)"
            >删除</el-button
          >
        </template>
      </NewPageFilter>
      <el-form
        :model="mountingsUseInfo.tableInfo"
        ref="tableForm"
        style="width: 100%"
      >
        <!-- 表格 -->
        <dialog-table
          ref="mountingsUseTable"
          :refresh="mountingsUseInfo.tableInfo.refresh"
          :init-curpage="mountingsUseInfo.tableInfo.initCurpage"
          v-model:data="mountingsUseInfo.tableInfo.data"
          :api="mountingsUseInfo.tableInfo.api"
          :query="mountingsUseInfo.tableInfo.query"
          :pager="true"
          :tabIndex="true"
          :field-list="mountingsUseInfo.tableInfo.fieldList"
          :handle="mountingsUseInfo.tableInfo.handle"
          :row-class-name="mountingsUseInfo.tableRowClassName"
          @handleEvent="selectMountingsTable"
        >
          <template v-slot:col-price="scope">
            <el-form-item
              :prop="`data.${scope.$index}.price`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveMoneyNoZeroAsset,
                        trigger: ['blur', 'change'],
                      },
                      {
                        required: scope.$index >= 0,
                        message: '请输入单价',
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.price"
                clearable
                controls-position="right"
                :precision="
                  $store.state.permission.systemConfig.assets_price_precision
                "
                @change="changePrice($event, scope.row, `price`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-qty="scope">
            <el-form-item
              :prop="`data.${scope.$index}.qty`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveNoAsset,
                        trigger: ['blur', 'change'],
                      },
                      {
                        required: scope.$index >= 0,
                        message: '请输入数量',
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="scope.row.qty"
                clearable
                controls-position="right"
                :precision="2"
                @change="changePrice($event, scope.row, `qty`)"
                :min="0"
                :max="999999999999999"
              />
            </el-form-item>
          </template>
          <template v-slot:col-useTime="scope">
            <el-form-item
              :prop="`data.${scope.$index}.useTime`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: validateUseTime,
                        trigger: 'blur',
                      },
                    ]
                  : []
              "
            >
              <el-date-picker
                v-model="scope.row.useTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </template>
        </dialog-table>
      </el-form>
    </page-dialog>
    <!-- 选择配件 -->
    <SelectAccessories
      v-if="accessoriesInfo.visible"
      v-model:show-dialog="accessoriesInfo.visible"
      :query="accessoriesInfo.query"
      :tableKey="accessoriesInfo.tableKey"
      @callback="changeAccessories"
    />
    <Select-fault
      v-if="seelctFault.visible"
      v-model:show-dialog="seelctFault.visible"
      :query="seelctFault.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectFaultCallback"
    />
    <add-fault
      v-if="tableDialogInfo.visible"
      v-model:show-dialog="tableDialogInfo.visible"
      :data="tableDialogInfo.data"
      @callback="addFaultCallback"
    />
    <SelectAssetResource
      v-if="selectAssetResourceInfo.visible"
      v-model:showDialog="selectAssetResourceInfo.visible"
      :query="selectAssetResourceInfo.query"
      :saveEmpty="true"
      :check-box="true"
      :highlight-row="false"
      @callback="SelectAssetResourceCallBack"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="maintenanceOrder">
import {
  getRepairPartsAffairPage,
  cannelMaintenceOrder,
  createRepairPartsAffair,
  faultConfirmMaintenceOrder,
  dealCompleteMaintenceOrder,
  repairDealAffair,
  passOnMaintenceOrder,
  acceptMaintenceOrder,
  getMaintenceOrderCustomizeListPage,
  delByMaintenanceIdRepairPartsAffair,
  getSelectUserWithPermission,
  summaryWorkingHours,
  excelMaintenanceOrder,
} from '@/api/repair.js'

import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElLoading, ElMessage } from 'element-plus'
import PageDialog from '@/components/PageDialog/index'
import axios from 'axios'
import PageForm from '@/components/PageForm/index'
import MaintenanceOrderModify from '@/views/repair/repairManage/maintenanceOrder/modify.vue'
import MaintenanceOrderDetail from '@/views/repair/repairManage/maintenanceOrder/details.vue'
import SelectRepairUser from '@/components/SelectUsers/selectMaintenanceUsers'
import SelectAccessories from '@/components/SelectAccessories/index'
import selectAsset from '@/components/SelectAsset/index'
import RepairOrderDetail from '@/views/repair/repairManage/repairOrder/details.vue'
import moment from 'moment'
import DialogTable from '@/components/DialogTable/index'
import addFault from './addFault.vue'

import {
  getDepotsSelectAllAndMaintenanceGroup,
  getDeptsSelectAllAndMaintenanceGroup,
} from '@/api/core'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const TableContainer = defineAsyncComponent(() =>
  import('@/components/TableContainer/index')
)
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)

const props = defineProps(['query'])

let validateFaultTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('故障发生时间不能大于当前时间！'))
  } else {
    callback()
  }
}
let validateCompleteTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('完工时间不能大于当前时间！'))
  } else {
    callback()
  }
}
let validateStartTime = (rule, value, callback) => {
  let endTime = registerInfo.formInfo.data.endTime
  if (endTime) {
    if (endTime < value) {
      callback(new Error('开始时间不能大于结束时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
let validateEndTime = (rule, value, callback) => {
  let startTime = registerInfo.formInfo.data.startTime
  if (startTime) {
    if (startTime > value) {
      callback(new Error('结束时间不能小于开始时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const tableDialogInfo = ref({
  data: {},
  visible: false,
  type: '',
})
const seelctFault = ref({
  visible: false,
  query: {},
})
const selectAssetResourceInfo = ref({
  visible: false,
  query: {
    assetId: '',
  },
})
const mountingsUseFormRefs = ref([])
const clearType = ref(true)
const slipSelectRequest = ref(true)

const listTypeInfo = reactive({
  typeList: [],
})
const filterInfo = reactive({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      assetSourceAuth: {
        asTbName: 'repair_order,repair_order',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
    },
    queryParams: {},
  },
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  searchList: [],
  btnList: [
    {
      event: exportExcel,
      label: '导出excel',
      type: 'button',
      show: proxy.$permission('maintenanceOrder:exportExcel'),
    },
  ],
})
const currentUser = ref(proxy.$store.state.user.userInfo.user.id)
const userType = ref(proxy.$store.state.user.userInfo.user.type)
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '接单',
        event: receiveOrder,
        show: proxy.$permission('maintenanceOrder:receiveOrder'),
        ifRender: function (row) {
          const canReceiveUserArr = row.pendReceiveUser
            ? row.pendReceiveUser.split(',')
            : []
          return (
            row.orderSource !== 2 &&
            row.status === 1 &&
            ((row.maintenanceUser &&
              row.maintenanceUser === -2 &&
              canReceiveUserArr.includes(currentUser.value + '')) ||
              canReceiveUserArr.length === 0 ||
              userType.value !== 'normal')
          )
        },
      },
      {
        label: '转交',
        event: turnOver,
        show: proxy.$permission('maintenanceOrder:turnOver'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 2 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      {
        label: '处理登记',
        event: handleRegister,
        show: proxy.$permission('maintenanceOrder:handleRegister'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 2 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      {
        label: '完工',
        event: finish,
        show: proxy.$permission('maintenanceOrder:finish'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 2 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      // 项目化代码
      {
        label: '确认',
        event: isSure,
        show: true,
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 8 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      {
        label: '故障确认',
        event: faultVerify,
        show: proxy.$permission('maintenanceOrder:faultVerify'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 2 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      {
        label: '配件使用',
        event: mountingsUse,
        show: proxy.$permission('maintenanceOrder:mountingsUse'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 2 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
      {
        label: '取消完工',
        popconfirmText: '取消完工后将改变数据,是否继续？',
        event: cancelFinish,
        show: proxy.$permission('maintenanceOrder:cancelFinish'),
        ifRender: function (row) {
          return (
            row.orderSource !== 2 &&
            row.status === 3 &&
            ((row.maintenanceUser && row.maintenanceUser === -2) ||
              row.maintenanceUser ===
                proxy.$store.state.user.userInfo.user.id ||
              proxy.$store.state.user.userInfo.user.type !== 'normal')
          )
        },
      },
    ],
  },
})
const printerInfo = reactive({
  visible: false,
  data: {},
})
const detailListInfo = reactive({
  visible: false,
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '维修单详情',
  id: '',
})
const repairDetailInfo = reactive({
  visible: false,
  title: '报修单详情',
  id: '',
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})

const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

const clickItem = ref({})

//转交相关
const turnOverInfo = reactive({
  visible: false,
  title: '',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleCloseTurnOver,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveTurnOver,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '转交给',
        value: 'acceptUserName',
        type: 'slot',
        required: true,
      },
      {
        label: '转交说明',
        value: 'dispatchDescribe',
        type: 'textarea',
      },
    ],
    rules: {
      acceptUserName: [
        {
          required: true,
          message: '请选择维修人员',
          trigger: 'change',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//处理登记相关
const registerInfo = reactive({
  visible: false,
  title: '处理登记',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseRegister, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveRegister,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {
      filePathList: [],
    },
    fieldList: [
      {
        label: '处理人',
        value: 'dealUserName',
        type: 'input',
        disabled: true,
      },

      {
        label: '开始时间',
        value: 'startTime',
        type: 'slot',
        required: true,
      },
      {
        label: '结束时间',
        value: 'endTime',
        type: 'slot',
        required: true,
      },
      {
        label: '处理进度(%)',
        value: 'dealRate',
        type: 'number',
        precision: 2,
        max: 100,
        // required: true,
      },
      {
        label: '工作说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: true,
      },
      {
        label: '附件',
        value: 'filePathList',
        type: 'slot',
        className: 'not-br',
      },
    ],
    rules: {
      startTime: [
        // {
        //   required: true,
        //   message: '请选择开始时间',
        //   trigger: 'change',
        // },
        {
          validator: validateStartTime,
          trigger: 'blur',
        },
      ],
      endTime: [
        // {
        //   required: true,
        //   message: '请选择结束时间',
        //   trigger: 'change',
        // },
        {
          validator: validateEndTime,
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: true,
          message: '请输入工作说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '110px',
  },
  uploadInfo: {
    action: axios.defaults.baseURL + '/pub/uploadfile',
    headers: {
      Authorization: proxy.$store.state.user.token,
    },
    loading: {},
    limit: 3,
    fileList: [],
    fileSize: proxy.$store.state.permission.systemConfig.max_file_size,
    fileType: [
      'png',
      'jpg',
      'jpeg',
      'pdf',
      'mp3',
      'm4a',
      'aac',
      'wav',
      'audio',
      'x-m4a',
      'doc',
      'docx',
      'xls',
      'xlsx',
    ],
  },
})
//完工相关
const finishInfo = reactive({
  visible: false,
  title: '完工',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFinish, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFinish,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '完工时间',
        value: 'completeTime',
        type: 'slot',
        // required: true,
      },
      {
        label: '处理结果',
        value: 'dealResult',
        type: 'select-model',
        // clearable: true,
        code: 'deal_result',
        required: true,
        // 确认状态为项目化代码
        onlyShowOption: ['0', '1', '2'],
      },
      {
        label: '合计工时(h)',
        value: 'dealTime',
        type: 'number',
        precision: 2,
        required: true,
      },
      {
        label: '维修服务费',
        value: 'serviceAmount',
        type: 'number',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '维修材料费',
        value: 'materialAmount',
        type: 'number',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
        disabled: true,
      },
      {
        label: '费用合计',
        value: 'sumAmount',
        type: 'number',
        disabled: true,
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '完工说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: proxy.$store.state.permission.systemConfig.repair_complete_describe_required == 1,
      },
    ],
    rules: {
      completeTime: [
        // {
        //   required: true,
        //   message: '请选择完工时间',
        //   trigger: 'change',
        // },
        {
          validator: validateCompleteTime,
          trigger: 'blur',
        },
      ],
      dealTime: [
        {
          required: true,
          message: '请输入合计工时',
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: proxy.$store.state.permission.systemConfig.repair_complete_describe_required == 1,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
      dealResult: [
        {
          required: true,
          message: '请xuan选择处理结果',
          trigger: 'change',
        },
      ],

      completeDescribe: [
        {
          required: true,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//故障确认相关
const faultVerifyInfo = reactive({
  visible: false,
  title: '故障确认',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFaultVerify, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFaultVerify,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '资产',
        value: 'assetName',
        type: 'input',
        disabled: true,
      },

      {
        label: '故障发生时间',
        value: 'faultTime',
        type: 'slot',
      },

      {
        label: '停机时长(h)',
        value: 'haltTime',
        type: 'number',
        // precision: 1,
      },
      {
        label: '故障部位',
        value: 'faultPart',
        type: 'slot',
      },

      {
        label: '故障描述',
        value: 'faultDescribe',
        type: 'slot',
        required: true,
        maxlength: 500,
      },

      {
        label: '故障原因',
        value: 'faultReason',
        type: 'textarea',
        maxlength: 500,
      },
      {
        label: '维修方案',
        value: 'maintenanceScheme',
        type: 'slot',
        maxlength: 500,
      },
    ],
    rules: {
      assetName: [
        {
          required: true,
          message: '请输入资产',
          trigger: 'change',
        },
      ],
      faultTime: [
        {
          validator: validateFaultTime,
          trigger: 'blur',
        },
      ],
      faultDescribe: [
        {
          required: true,
          message: '请输入故障描述',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//配件使用相关
const mountingsUseInfo = reactive({
  orderId: '',
  maintenanceOrderId: '',
  visible: false,
  title: '配件使用',
  btLoading: false,
  type: '',
  msg: '',
  width: '75%',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleCloseMountingsUse,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: saveMountingsUse,
      show: true,
    },
  ],
  // 过滤相关配置
  filterInfo: {
    query: {
      customizeUserVO: {},
      queryMap: {},
    },
    list: [
      {
        label: '添加',
        type: 'button',
        event: addMountings,
        show: true,
      },
      {
        label: '删除',
        type: 'slot',
        value: 'removeMountings',
      },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    api: getRepairPartsAffairPage,
    query: {
      maintenanceId: '',
      sort: 'create_time desc',
    },
    fieldList: [
      {
        label: '配件名称',
        value: 'commonName',
      },
      {
        label: '规格',
        value: 'standard',
      },
      {
        label: '计量单位',
        value: 'unitName',
      },
      {
        label: '单价',
        value: 'price',
        type: 'slot',
      },
      {
        label: '数量',
        value: 'qty',
        type: 'slot',
      },
      {
        label: '金额',
        value: 'sumAmount',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
      },
      {
        label: '更换日期',
        value: 'useTime',
        type: 'slot',
      },
    ],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '50',
      btList: [
        {
          label: '删除',
          event: removeMountings,
          popconfirmText: '删除后将改变数据,是否继续？',
          show: true,
        },
      ],
    },
  },
})
let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
//选择配件
const accessoriesInfo = reactive({
  visible: false,
  tableKey:
    'accessoriesArchivesDialog-com.slip.spd.entity.vo.asset.settings.AccessoriesArchivesVO',
  query: {
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
  },
})
//选择报修单
const repairOrderInfo = reactive({
  visible: false,
  query: {
    // status:1
  },
})
const canReminder = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter((item) => item.status !== 2).length
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'maintenanceOrder' && el.url === val.url) {
                detailInfo.visible = false
                turnOverInfo.visible = false
                registerInfo.visible = false
                finishInfo.visible = false
                faultVerifyInfo.visible = false
                mountingsUseInfo.visible = false
                repairDetailInfo.visible = false
                advancedSearchInfo.visible = false
                preferenceInfo.visible = false
                accessoriesInfo.visible = false
                selectRepairUserInfo.visible = false

                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
watch(
  () => registerInfo.formInfo.data.endTime,
  (val) => {
    console.log(
      registerInfo.formInfo.data.endTime,
      'registerInfo.formInfo.data.endTime'
    )
  }
)
onDeactivated(() => {
  stopWatch()
})
watch(
  () => mountingsUseInfo.tableInfo.data,
  (val) => {
    if (val.length) {
      let ids = []
      val.forEach((row) => {
        ids.push(row.productId)
      })
      accessoriesInfo.query.id.value = String(ids)
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(val.length)
      }
    } else {
      accessoriesInfo.query.id.value = ''
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(0)
      }
    }
  },
  {
    deep: true,
  }
)
watch(
  () => finishInfo.formInfo.data,
  (val) => {
    let materialAmount = val.materialAmount || 0
    let serviceAmount = val.serviceAmount || 0
    val.sumAmount = proxy.$fn.accAdd(serviceAmount, materialAmount)
  },
  {
    deep: true,
  }
)

let obj = {
  repairNo: {
    label: '报修单号',
    value: 'repairNo',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  notRepairTransferToThirdValue: {
    label: '是否转院外',
    value: 'notRepairTransferToThirdValue',
    asValue: 'notRepairTransferToThird',
    componentType: 'select-model',
    code: 'yes_or_no',
    show: false,
    hidden: true,
  },
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'maintenance_order_status',
    show: false,
    hidden: true,
  },
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '2',
    },
    api: getDepotsSelectAllAndMaintenanceGroup,
    show: false,
    hidden: true,
  },
  useDeptName: {
    label: '使用部门',
    value: 'useDeptName',
    asValue: 'useDeptId',
    query: {
      deptAuth: 'id',
      status: 1,
    },
    api: getDeptsSelectAllAndMaintenanceGroup,
    componentType: 'slip-select',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function validateUseTime(rule, value, callback) {
  let currentTime = moment(new Date()).format('YYYY-MM-DD')
  let updateTime = moment(value).format('YYYY-MM-DD')
  if (updateTime > currentTime) {
    callback(new Error('更换日期不能大于当前日期！'))
  } else {
    callback()
  }
}
//导出excel
async function exportExcel() {
  dialogInfo.value.flag = true
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: dialogInfo.value.flag,
  }
  excelMaintenanceOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function selectMountingsTable(event, data) {
  switch (event) {
    case 'tableCheck':
      mountingsUseInfo.tableInfo.selections = [...data]
      break
  }
}
//单价
function changePrice(e, row, str) {
  if (str === 'qty') {
    row.sumAmount = proxy.$fn.accMul(e, row.price)
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.price);
  } else if (str === 'price') {
    row.sumAmount = proxy.$fn.accMul(e, row.qty)
    // row.price = e;
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.qty);
  }
}
//删除附件
function uploadRemove(file, fileList) {
  registerInfo.formInfo.data.filePathList = fileList
}
function handleExceed() {
  proxy.$message.warning(` 只能上传 ${registerInfo.uploadInfo.limit} 个文件`)
}
function beforeProductUpload(file) {
  //验证文件格式
  let fileTypeArr = file.name.split('.')[file.name.split('.').length - 1]
  if (registerInfo.uploadInfo.fileType.indexOf(fileTypeArr) === -1) {
    proxy.$message.error(
      `文件格式不正确, 请上传 ${registerInfo.uploadInfo.fileType.join(
        ' / '
      )} 格式文件!`
    )
    return false
  }
  let file_type_list = proxy.$store.state.permission.dict['file_type_list']
  if (file_type_list && file_type_list.length) {
    let uploadType = file.name.split('.')[file.name.split('.').length - 1]
    let file_type_list_arr = []
    file_type_list.forEach((item) => {
      file_type_list_arr.push(item.code)
    })
    if (!String(file_type_list_arr).includes(uploadType)) {
      proxy.$message.error({
        message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
  }
  //验证文件大小
  const maxFileSize = file.size / 1024 / 1024 < registerInfo.uploadInfo.fileSize
  if (!maxFileSize) {
    proxy.$message.error(
      `上传文件大小不能超过${registerInfo.uploadInfo.fileSize}Mb！`
    )
    return false
  }
  //发生请求时打开加载动画
  registerInfo.uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
//上传附件
function uploadAttachment(resp, file, fileList) {
  console.log(resp, file, fileList, 'resp, file, fileList')
  registerInfo.uploadInfo.loading.close()
  if (resp && resp.success) {
    file.filePath = resp.data[0]
    registerInfo.formInfo.data.filePathList = fileList
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  registerInfo.uploadInfo.loading.close()
}
function openRepairUserWindow() {
  selectRepairUserInfo.visible = true
}
function selectRepairUserCallBack(row) {
  if (row) {
    turnOverInfo.formInfo.data['acceptUser'] = row.userId
    turnOverInfo.formInfo.data['acceptUserName'] = row.name
  } else {
    turnOverInfo.formInfo.data['acceptUser'] = ''
    turnOverInfo.formInfo.data['acceptUserName'] = ''
  }
}
function pageInfo(obj) {
  page = obj
}
function handleCloseMountingsUse() {
  mountingsUseInfo.visible = false
}
function handleCloseFaultVerify() {
  faultVerifyInfo.visible = false
}
function handleCloseRegister() {
  registerInfo.visible = false
}
function handleCloseFinish() {
  finishInfo.visible = false
}
function handleCloseTurnOver() {
  turnOverInfo.visible = false
}
function showProductDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.visible = true
  detailInfo.title = '维修单详情'
  detailInfo.id = row.id
}
function showRepairDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  repairDetailInfo.visible = true
  repairDetailInfo.title = '报修单详情'
  repairDetailInfo.id = row.repairId
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
function openAssetResource() {
  selectAssetResourceInfo.value.visible = true
  selectAssetResourceInfo.value.query.assetId =
    faultVerifyInfo.formInfo.data['assetId']
}
function SelectAssetResourceCallBack(data) {
  if (data && data.length) {
    let resourceName = data.map((item) => item.resourceName)
    faultVerifyInfo.formInfo.data.faultPart =
      resourceName && resourceName.length ? resourceName.toString() : ''
  } else {
    faultVerifyInfo.formInfo.data.faultPart = ''
  }
}
//接单
function receiveOrder(row) {
  if (
    (row.maintenanceUser && row.maintenanceUser === -2) ||
    row.maintenanceUser === proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  ) {
    acceptMaintenceOrder(row.id).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy.$message.warning('当前用户不是该单据的维修人，不可操作该单据！')
  }
}
//转交
function turnOver(row) {
  if (
    (row.maintenanceUser && row.maintenanceUser === -2) ||
    row.maintenanceUser === proxy.$store.state.user.userInfo.user.id ||
    proxy.$store.state.user.userInfo.user.type !== 'normal'
  ) {
    turnOverInfo.formInfo.data = {}
    turnOverInfo.visible = true
    turnOverInfo.title = '转交'
    turnOverInfo.formInfo.data.orderId = row.id
    turnOverInfo.formInfo.data.orderType = 54
    selectRepairUserInfo.query.userIdNotIn = row.maintenanceUser
    selectRepairUserInfo.query.orgId =
      row.maintenanceId === -2 ? '' : row.maintenanceId
    selectRepairUserInfo.query.assetId = row.assetId === -2 ? '' : row.assetId
    selectRepairUserInfo.query.deptId =
      row.useDeptId === -2 ? '' : row.useDeptId
    selectRepairUserInfo.query.depotId = row.depotId === -2 ? '' : row.depotId
    selectRepairUserInfo.query.assetClassifyId =
      row.classifyType === -2 ? '' : row.classifyType
    selectRepairUserInfo.query.notAssetRepairType =
      row.notAssetRepairType === -2 ? '' : row.notAssetRepairType
    proxy.$nextTick(() => {
      turnOverInfo.formInfo.ref.clearValidate()
    })
  } else {
    proxy.$message.warning('当前用户不是该单据的维修人，不可操作该单据！')
  }
}

//转交保存
function saveTurnOver() {
  turnOverInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      passOnMaintenceOrder(turnOverInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        turnOverInfo.visible = false
      })
    }
  })
}
//处理登记
function handleRegister(row) {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (row.maintenanceUser != proxy.$store.state.user.userInfo.user.id) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  registerInfo.formInfo.data = {}
  registerInfo.visible = true
  registerInfo.formInfo.data.dealUser = proxy.$store.state.user.userInfo.user.id
    ? proxy.$store.state.user.userInfo.user.id
    : ''
  registerInfo.formInfo.data.dealUserName = proxy.$store.state.user.userInfo
    .user.name
    ? proxy.$store.state.user.userInfo.user.name
    : ''
  registerInfo.formInfo.data.orderId = row.repairId
  registerInfo.formInfo.data.filePathList = []
  registerInfo.uploadInfo.fileList = []
  registerInfo.formInfo.data.orderType = 54
  registerInfo.formInfo.data.maintenanceOrderId = row.id
  proxy.$nextTick(() => {
    registerInfo.formInfo.ref.clearValidate()
  })
}
//处理登记保存
function saveRegister() {
  registerInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      repairDealAffair(registerInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        registerInfo.visible = false
      })
    }
  })
}
//完工
function finish(row) {
  summaryWorkingHours({
    orderId: row.repairId,
    orderType: 54,
  }).then((res) => {
    if (res && res.success) {
      finishInfo.formInfo.data.dealTime = res.data
    }
  })
  finishInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
  }
  finishInfo.title = '完工'
  finishInfo.formInfo.fieldList.forEach((item) => {
    if (item.value === 'dealResult') {
      item.onlyShowOption = ['0', '1', '2']
    }
  })
  finishInfo.formInfo.data.id = row.id
  finishInfo.formInfo.data.materialAmount = row.materialAmount
  finishInfo.formInfo.data.serviceAmount = row.serviceAmount
  finishInfo.visible = true
  proxy.$nextTick(() => {
    finishInfo.formInfo.ref.clearValidate()
  })
}
//确认
function isSure(row) {
  summaryWorkingHours({
    orderId: row.repairId,
    orderType: 54,
  }).then((res) => {
    if (res && res.success) {
      finishInfo.formInfo.data.dealTime = res.data
    }
  })
  finishInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
  }
  finishInfo.visible = true
  finishInfo.title = '确认'
  finishInfo.formInfo.fieldList.forEach((item) => {
    if (item.value === 'dealResult') {
      item.onlyShowOption = ['0', '1']
    }
  })
  finishInfo.formInfo.data.id = row.id
  finishInfo.formInfo.data.materialAmount = row.materialAmount
  finishInfo.formInfo.data.serviceAmount = row.serviceAmount
  proxy.$nextTick(() => {
    finishInfo.formInfo.ref.clearValidate()
  })
}
//完工保存
function saveFinish() {
  finishInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      dealCompleteMaintenceOrder(finishInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        finishInfo.visible = false
      })
    }
  })
}
//取消完工
function cancelFinish(row) {
  cannelMaintenceOrder(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//故障确认
function faultVerify(row) {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (row.maintenanceUser != proxy.$store.state.user.userInfo.user.id) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  faultVerifyInfo.formInfo.data = {}
  faultVerifyInfo.visible = true
  faultVerifyInfo.formInfo.data.id = row.id
  faultVerifyInfo.formInfo.data['faultTime'] = row.faultTime
  faultVerifyInfo.formInfo.data['haltTime'] = row.haltTime
  faultVerifyInfo.formInfo.data['faultReason'] = row.faultReason
  faultVerifyInfo.formInfo.data['faultPart'] = row.faultPart
  faultVerifyInfo.formInfo.data['faultDescribe'] = row.faultDescribe
  faultVerifyInfo.formInfo.data['maintenanceScheme'] = row.maintenanceScheme
  faultVerifyInfo.formInfo.data['assetName'] = row.assetName
  faultVerifyInfo.formInfo.data['assetId'] = row.assetId
  faultVerifyInfo.formInfo.data['faultLibraryId'] = row.faultLibraryId
  clickItem.value = row
  proxy.$nextTick(() => {
    faultVerifyInfo.formInfo.ref.clearValidate()
  })
}
//故障确认保存
function saveFaultVerify() {
  faultVerifyInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      faultConfirmMaintenceOrder(faultVerifyInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        faultVerifyInfo.visible = false
      })
    }
  })
}
//配件使用
function mountingsUse(row) {
  if (proxy.$store.state.user.userInfo.user.type === 'normal') {
    if (row.maintenanceUser != proxy.$store.state.user.userInfo.user.id) {
      proxy.$message.warning('当前登录人员不是该维修单据的维修人员！')
      return
    }
  }
  mountingsUseInfo.visible = true
  mountingsUseInfo.tableInfo.data = []
  mountingsUseInfo.orderId = row.repairId
  mountingsUseInfo.maintenanceOrderId = row.id
  mountingsUseInfo.tableInfo.query.maintenanceOrderId = row.id
  mountingsUseInfo.orderNo = row.orderNo
  mountingsUseInfo.repairId = row.repairId
  mountingsUseInfo.repairNo = row.repairNo

  mountingsUseInfo.tableInfo.refresh = Math.random()
  setTimeout(() => {
    getMountingsUseList()
  }, 0)
}
//添加配件
function addMountings() {
  accessoriesInfo.visible = true
}
function getMountingsUseList() {
  mountingsUseInfo.tableInfo.refresh = Math.random()
}
//删除配件
function removeMountings(row = undefined) {
  if (row) {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (item) => item.productId !== row.productId
    )
  } else {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (row) => {
        return !mountingsUseInfo.tableInfo.selections.includes(row)
      }
    )
  }
}
//选择配件
function changeAccessories(data) {
  if (data.length) {
    data.forEach((item) => {
      let obj = {
        productId: item.id,
        productName: item.commonName,
        price: item.referencePrice,
        ...item,
        useTime:
          item.useTime || moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      }
      mountingsUseInfo.tableInfo.data.push(obj)
    })
    accessoriesInfo.visible = false
  }
}
//配件使用保存
function saveMountingsUse() {
  let data = mountingsUseInfo.tableInfo.data
  if (data.length) {
    proxy.$refs['tableForm'].validate((valid) => {
      if (valid) {
        let arr = []

        data.forEach((item) => {
          arr.push({
            commonName: item.commonName,
            productCode: item.productCode,
            unitName: item.unitName,
            standard: item.standard,
            productId: item.productId,
            calcQty: item.qty,
            qty: item.qty,
            orderId: mountingsUseInfo.orderId,
            orderType: 54,
            price: item.price,
            sumAmount: item.sumAmount,
            useTime: item.useTime,
            // maintenanceOrderId: ,
            maintenanceOrderId: mountingsUseInfo.maintenanceOrderId,
            maintenanceNo: mountingsUseInfo.orderNo,
            repairId: mountingsUseInfo.repairId,
            repairNo: mountingsUseInfo.repairNo,
          })
        })
        createRepairPartsAffair(arr).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
          mountingsUseInfo.visible = false
        })
      }
    })
  } else {
    delByMaintenanceIdRepairPartsAffair(
      mountingsUseInfo.maintenanceOrderId
    ).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
      mountingsUseInfo.visible = false
    })
  }
}
// 创建
function create() {
  repairOrderInfo.visible = true
}
//选择报修单
function callbackRepairOrder(row) {
  if (row) {
    modifyInfo.visible = true
    modifyInfo.title = '新增维修单'
    modifyInfo.id = row.id
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!props.slipSelectRequest)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'core_asset',
      columnName: 'use_dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.vlaue
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
async function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}

function clearSearch() {
  clearType.value = !clearType.vlaue
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'repairMaintenceOrderList-com.slip.spd.entity.vo.repair.MaintenanceOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        if (item.value === 'notRepairTransferToThirdValue') {
          item.slot = true
        }
        item.event = search
      })
      console.log(11111111)
      console.log(filterInfo.searchList)
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getMaintenceOrderCustomizeListPage
      getList()
    }
  })
}

// 故障库
function openFault() {
  console.log(clickItem.value)
  seelctFault.value.visible = true
  seelctFault.value.query['repairTypeMult'] = clickItem.value.repairType
  seelctFault.value.query['classifyTypeMult'] = clickItem.value.classifyType
  seelctFault.value.query['classifyTypeValue'] =
    clickItem.value.classifyTypeValue
  seelctFault.value.query['notAssetRepairTypeMult'] =
    clickItem.value.notAssetRepairType
}

function selectFaultCallback(row) {
  console.log(row)
  faultVerifyInfo.formInfo.data.faultDescribe = row.faultDescribe
  faultVerifyInfo.formInfo.data.faultReason = row.faultReason
  faultVerifyInfo.formInfo.data.maintenanceScheme = row.maintenanceScheme
  faultVerifyInfo.formInfo.data.faultLibraryId = row.id
}
function addFaultCallback(row) {
  console.log(row)
}

function _addFault() {
  console.log(clickItem.value)
  tableDialogInfo.value.visible = true
  tableDialogInfo.value.type = 'update'
  tableDialogInfo.value.data = {
    ...clickItem.value,
    ...faultVerifyInfo.formInfo.data,
  }
}
</script>

<style scoped></style>
